/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.HashMap;
import java.util.Iterator;

import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.AndroidUtil;
import org.gl.utils.Dateutil;
import org.gl.utils.lg;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.dialog.DatePickDialogImpOnclick;

public class CarRecordFragment extends BaseFragment implements
		View.OnClickListener {
	String TAG = "CarRecordFragment";
	/**
	 * set for current km next km next time
	 */
	EditText et_fromDate, et_toDate;
	LinearLayout ll_container;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.car_record, container, false);
		String fromDate = Dateutil.getNextDayString(-30);
		String toDate = Dateutil
				.getTimeString(Dateutil.SimpleDateFormat__YYYYMMDD,
						System.currentTimeMillis());
		et_fromDate = (EditText) view.findViewById(R.id.et_from);
		et_fromDate.setText(fromDate);
		et_fromDate.setFocusable(false);

		et_toDate = (EditText) view.findViewById(R.id.et_to);
		et_toDate.setText(toDate);
		et_toDate.setFocusable(false);

		ll_container = (LinearLayout) view
				.findViewById(R.id.ll_user_record_container);
		initData(fromDate, toDate);
		et_fromDate
				.setOnClickListener(new DatePickDialogImpOnclick(et_fromDate));
		et_toDate.setOnClickListener(new DatePickDialogImpOnclick(et_toDate));
		et_toDate.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(et_fromDate.getText())) {
					et_fromDate.requestFocus();
					et_fromDate
							.setError(getString(R.string.error_field_required));
					return;
				}
				if (TextUtils.isEmpty(et_toDate.getText())) {
					et_toDate.requestFocus();
					et_toDate
							.setError(getString(R.string.error_field_required));
					return;
				}
				initData(et_fromDate.getText().toString(), et_toDate.getText()
						.toString());
			}
		});
//		"fule":"9.1","mileNight":"1550.11","driveTimeNight":"45.47","acceleration":"0",
//		"mile":"2697.96","tvspeed":"36.00","highestSpeed":"145","speedU120":"35.47",
//		"brakes":"0","driveTime":"73.42"
		nameUnitMap.put("mile", new String[]{"区间行驶里程"," km"});
		nameUnitMap.put("mileNight", new String[]{"夜间行驶里程"," km"});
		nameUnitMap.put("driveTimeNight", new String[]{"夜间行驶时间"," 小时"});
		nameUnitMap.put("fule", new String[]{"百公里油耗"," 升"});
		nameUnitMap.put("acceleration", new String[]{"急加速次数"," "});
		nameUnitMap.put("tvspeed", new String[]{"平均速度"," km/h"});
		nameUnitMap.put("highestSpeed", new String[]{"最高速度"," km/h"});
		nameUnitMap.put("speedU120", new String[]{"超速行驶时间"," 小时"});
		nameUnitMap.put("brakes", new String[]{"急减速次数"," "});
		nameUnitMap.put("driveTime", new String[]{"驾驶时间"," 小时"});
		view.findViewById(R.id.iv_user_add).setClickable(true);
		view.findViewById(R.id.iv_user_add).setOnClickListener(this);
		return view;
	}

	/**
	 * 输入验证
	 * 
	 * @param fromDate
	 * @param toDate
	 */
	private void initData(String fromDate, String toDate) {
		if (TextUtils.isEmpty(fromDate)) {
			et_fromDate.requestFocus();
			et_fromDate.setError(getString(R.string.error_field_required));
			return;
		}
		if (TextUtils.isEmpty(toDate)) {
			et_toDate.requestFocus();
			et_toDate.setError(getString(R.string.error_field_required));
			return;
		}
		if (Dateutil.convert2long(fromDate, "yyyy-MM-dd") > Dateutil
				.convert2long(toDate, "yyyy-MM-dd")) {
			et_toDate.requestFocus();
			et_toDate.setError(getString(R.string.err_date_end_from));
			return;
		}
		DataSources ds = new DataSources();
		ds.getCarerRecord(fromDate, toDate,
				IntentExtraDataKeyValue.getUserIdentifier(),
				new AjaxCallBackProxy<String>(view.findViewById(R.id.loading)) {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						lg.i(TAG, t);
						if (t == null) {
							loadFailed("result is null");
						} else {

						}
						int isfinish = 0;
						String message = "";
						JSONObject j = null;
						try {
							j = new JSONObject(t);
							isfinish = j.optInt("code");
							message += j.optString("reason");
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							if (isfinish != 0) {
								loadFailed(message);
								ll_container.removeAllViews();
							} else {
								loadSuccessed();
								setValue(j);
							}
						}

					}
				});

	}
	HashMap<String, String[]> nameUnitMap= new HashMap<String, String[]>();
	protected void setValue(JSONObject j) {
		if (j == null || context == null) {
			return;
		}
		ll_container.removeAllViews();
		String text = "";
		TextView tv;
		TextView tv_value;
		LinearLayout ll;
		boolean ishas = (j.optString("isok") != null)
				&& j.optString("isok").equals("true");
		if (!ishas) {
			tv = new TextView(context);
			tv.setText("NO DATA!!");
			ll_container.addView(tv);
		} else {
			int left = (int) AndroidUtil.dipToPx(4);
			int heigh = (int) AndroidUtil.dipToPx(16);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1,-heigh);
			LinearLayout.LayoutParams lptv = new LinearLayout.LayoutParams(-1,-1);
			lptv.weight = 1.5f;
			LinearLayout.LayoutParams lptv2 = new LinearLayout.LayoutParams(-1,-1);
			lptv.weight = 1.5f;
			JSONObject j2 = j.optJSONObject("total");
			@SuppressWarnings("unchecked")
			Iterator<Object> array = j2.keys();
			while (array.hasNext()) {
				text = array.next().toString();
				String[] nameUnit = nameUnitMap.get(text);
				ll = new LinearLayout(context);
				ll.setWeightSum(3);
				ll.setLayoutParams(lp);
				ll.setPadding(left, left, left, left);
				
				tv = new TextView(context);
				tv.setLayoutParams(lptv);
				tv.setGravity(Gravity.LEFT);
				tv.setTextColor(0xff02457d);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
				tv.setText(nameUnit[0]+": ");
				ll .addView(tv);
				
				tv_value = new TextView(context);
				tv_value.setLayoutParams(lptv2);
				tv_value.setTextColor(0xffFFFFFF);
				tv_value.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
				tv_value.setText(""+j2.opt(text)+nameUnit[1]);
				ll .addView(tv_value);
				
//				tv.setText(text + ":" + j2.opt(text));
				ll_container.addView(ll);
			}
		}
	}

	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_user_add:
			initData(et_fromDate.getText().toString(), et_toDate.getText()
					.toString());
			break;

		default:
			break;
		}

	}
}